package com.liu.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Scanner;

import org.json.JSONObject;

import com.liu.crypto.Aes;
import com.liu.keeppwd.MainActivity;

import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public abstract class MySocket implements Runnable {
	MyHandler mHandler;
	String msg;
	String Ip;
	int port;
	String errMsg;
	boolean isReadRes;
	String resStr;

	public abstract void OnSuccessCallBack(String resStr);

	public abstract void OnErrorCallBack(String msg);

	public static boolean checkConn(String Ip, int port, String txmy) {
		boolean res = false;
		try {
			Socket socket = new Socket(Ip, port);
			OutputStream os = socket.getOutputStream();
			JSONObject obj = new JSONObject();
			obj.put("type", "4");
			obj.put("v1", "");
			obj.put("v2", "");
			String tmpNr = obj.toString();
			tmpNr = Aes.Encrypt(txmy, tmpNr);

			tmpNr += "\r\n";
			os.write(tmpNr.getBytes());
			InputStream ins = socket.getInputStream();
			char c = (char) ins.read();
			String resStr = "";
			while (c != -1 && c != '\0') {
				resStr += c;
				c = (char) ins.read();
			}
			if ("1".equals(resStr)) {
				res = true;
			}
			ins.close();
			os.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	public void sendMsg(String msg, String Ip, int port, boolean isReadRes) {
		mHandler = new MyHandler() {

			@Override
			public void OnSuccess() {
				OnSuccessCallBack(resStr);
			}

			@Override
			public void OnFinish() {

			}

			@Override
			public void OnError() {
				OnErrorCallBack(errMsg);
			}
		};
		this.msg = msg;
		this.Ip = Ip;
		this.isReadRes = isReadRes;
		this.port = port;
		new Thread(this).start();
	}

	private boolean send() {
		try {
			Socket socket = new Socket(Ip, port);
			OutputStream os = socket.getOutputStream();
			msg += "\r\n";
			os.write(msg.getBytes());
			InputStream ins = socket.getInputStream();
			char c = (char) ins.read();
			resStr = "";
			while (c != -1 && c != '\0') {
				resStr += c;
				c = (char) ins.read();
			}
			ins.close();
			os.close();
			socket.close();
			return true;
		} catch (Exception ex) {
			errMsg = ex.getMessage();
		}
		return false;
	}

	public void run() {
		Message msg = null;
		if (!send()) {
			if (!send()) {
				msg = mHandler.obtainMessage(MyHandler.MessType_Error);
			}
		}
		if (msg == null) {
			msg = mHandler.obtainMessage(MyHandler.MessType_Succe);
		}
		mHandler.sendMessage(msg);
	}
}
